package com.shure.surdes.modules.dict.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shure.surdes.common.query.condition.Condition;
import com.shure.surdes.common.result.R;
import com.shure.surdes.common.result.Result;
import com.shure.surdes.modules.dict.domain.Dict;
import com.shure.surdes.modules.dict.domain.DictType;
import com.shure.surdes.modules.dict.query.DictQuery;
import com.shure.surdes.modules.dict.query.DictTypeQuery;
import com.shure.surdes.modules.dict.service.IDictService;
import com.shure.surdes.modules.dict.service.IDictTypeService;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dict")
public class DictController {

    @Resource
    private IDictService dictService;

    @Resource
    private IDictTypeService dictTypeService;

    /*** 字典类型的接口 */

    @GetMapping("type/list")
    public R getTypeList(@Validated DictTypeQuery query) {
        LambdaQueryWrapper<DictType> wrapper = Condition.getLambdaQueryWrapper(query);
        Page<DictType> page = dictTypeService.page(query.getPage(), wrapper);
        return Result.ok(page);
    }

    @GetMapping("type/{typeId}")
    public R getType(@PathVariable("typeId") Long typeId) {
        return Result.ok(dictTypeService.getById(typeId));
    }

    @PostMapping("type/saveOrUpdate")
    public R saveOrUpdate(@RequestBody DictType dictType) {
        return Result.ok(dictTypeService.saveOrUpdate(dictType));
    }

    @DeleteMapping("type/delete/{typeId}")
    public R deleteType(@PathVariable("typeId") Long typeId) {
        return Result.ok(dictTypeService.removeById(typeId));
    }


    /*** 数据字典的接口 */

    @GetMapping("list/{dictType}")
    public R list(@PathVariable("dictType") String dictType) {
        List<Dict> list = dictService.list(new LambdaQueryWrapper<Dict>().eq(Dict::getTypeCode, dictType));
        if (list.isEmpty()) {
            list = dictService.list(new LambdaQueryWrapper<Dict>().eq(Dict::getTypeId, dictType));
        }
        return Result.ok(list);
    }

    @GetMapping("list")
    public R list(@Validated DictQuery query) {
        LambdaQueryWrapper<Dict> wrapper = Condition.getLambdaQueryWrapper(query);
        List<Dict> list = dictService.list(wrapper);
        return Result.ok(list);
    }

    @GetMapping("{dictId}")
    public R getDict(@PathVariable("dictId") Long dictId) {
        return Result.ok(dictService.getById(dictId));
    }

    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody Dict dict) {
        return Result.ok(dictService.saveOrUpdate(dict));
    }

    @DeleteMapping("delete/{dictId}")
    public R deleteDict(@PathVariable("dictId") Long dictId) {
        return Result.ok(dictService.removeById(dictId));
    }
}
